﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;

namespace QAQ
{
    class GCPacket
    {
        public int id;
        public string pw;
        public bool valid;
        public bool sent;
        public bool ack;

        public GCPacket()
        {
            this.clear();
        }

        public bool isValid()
        {
            return (true == valid) &&
                   (id > 0)&&
                   (pw != "");
        }

        public bool contentValid()
        {
            return (id > 0) &&
                   (pw != "");
        }

        public void clear()
        {
            id = -5;
            pw = "";
            valid = false;
            sent = true;
            ack = true;
        }

        public void GenerateKey()
        {
            this.pw = GetRandomAlphanumericString(15);
        }

        public static string GetRandomAlphanumericString(int length)
        {
            const string KeySpace =
                "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
                "abcdefghijklmnopqrstuvwxyz" +
                "0123456789";
            return GetRandomString(length, KeySpace);
        }

        public static string GetRandomString(int length, IEnumerable<char> characterSet)
        {
            if (length < 0)
                throw new ArgumentException("length must not be negative", "length");
            if (length > int.MaxValue / 8) // 250 million chars ought to be enough for anybody
                throw new ArgumentException("length is too big", "length");
            if (characterSet == null)
                throw new ArgumentNullException("characterSet");
            var characterArray = characterSet.Distinct().ToArray();
            if (characterArray.Length == 0)
                throw new ArgumentException("characterSet must not be empty", "characterSet");

            var bytes = new byte[length * 8];
            new RNGCryptoServiceProvider().GetBytes(bytes);
            var result = new char[length];
            for (int i = 0; i < length; i++)
            {
                ulong value = BitConverter.ToUInt64(bytes, i * 8);
                result[i] = characterArray[value % (uint)characterArray.Length];
            }
            return new string(result);
        }

    }
}
